<template>
  <div style="height: 100%; width: 100%">
    <div id="cesiumContainer"></div>
    <div id="animationContainer"></div>
  </div>
</template>

<script>


export default {
  data() {
    return {
      viewer: null
    }
  },
  mounted() {
    this.initCesium()
    this.addCesiumTimeInterval(this.viewer)
  },
  methods: {
    initCesium() {
      Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJjZGViNmIwOS0zOWY3LTQ0ZTYtYjg5Yi1jNDEyYzAzZmY1ZmUiLCJpZCI6MTE2OTA2LCJpYXQiOjE2Njk5NjE5NTB9.nN-KM-HnA5STxtweph2Rly5Y9O7bqX1khZKYQlcevHw';


      this.viewer = new Cesium.Viewer('cesiumContainer', {
        animation: true,
        baseLayerPicker: false,
        fullscreenButton: false,
        geocoder: false,
        homeButton: false,
        infoBox: true,
        sceneModePicker: false,
        navigationHelpButton: false,
        scene3DOnly: true,
        timeline: true,
        selectionIndicator: false,//是否显示选取指示器组件
        shouldAnimate: true,     //自动播放动画控件
        shadows: true,//是否显示光照投射的阴影
        terrainShadows: Cesium.ShadowMode.RECEIVE_ONLY,//地质接收阴影
        sceneMode: Cesium.SceneMode.SCENE3D,
        terrainProvider: new Cesium.CesiumTerrainProvider({//地质开挖必须是cesium提供的地形
          url: Cesium.IonResource.fromAssetId(1),
          requestVertexNormals: true,//顶点法线效果
          requestWaterMask: true//水效果
        })
      })
      //地质开挖不能有深度测试，有深度测试会被遮盖
      this.viewer.scene.globe.depthTestAgainstTerrain = false;
      this.viewer._cesiumWidget._creditContainer.style.display = 'none' //	去除版权信息
    },
    addCesiumTimeInterval(viewer) {
      //烟雾实体初始化参数
      let viewModel = {
        emissionRate: 5.0,
        gravity: 0.0,
        minimumParticleLife: 1.2,
        maximumParticleLife: 1.2,
        minimumSpeed: 1.0,
        maximumSpeed: 4.0,
        startScale: 1.0,
        endScale: 5.0,
        particleSize: 25.0
      };
      function computeModelMatrix(entity, time) {
        return entity.computeModelMatrix(time, new Cesium.Matrix4());
      }
      var emitterModelMatrix = new Cesium.Matrix4();
      var translation = new Cesium.Cartesian3();
      var rotation = new Cesium.Quaternion();
      var hpr = new Cesium.HeadingPitchRoll();
      var trs = new Cesium.TranslationRotationScale();
      function computeEmitterModelMatrix() {
        hpr = Cesium.HeadingPitchRoll.fromDegrees(0.0, 0.0, 0.0, hpr);
        trs.translation = Cesium.Cartesian3.fromElements(
          -14.0,
          0.0,
          1.4,
          translation
        );
        trs.rotation = Cesium.Quaternion.fromHeadingPitchRoll(hpr, rotation);

        return Cesium.Matrix4.fromTranslationRotationScale(
          trs,
          emitterModelMatrix
        );
      }

      viewer.scene.globe.enableLighting = true;
      let data = [
        {
          longitude: 116.405419,
          dimension: 39.918034,
          height: 0,
          time: 0
        }, {
          longitude: 116.2821,
          dimension: 39.918145,
          height: 0,
          time: 40
        }, {
          longitude: 115.497402,
          dimension: 39.344641,
          height: 70000,
          time: 100
        }, {
          longitude: 107.942392,
          dimension: 29.559967,
          height: 70000,
          time: 280
        }, {
          longitude: 106.549265,
          dimension: 29.559967,
          height: 0,
          time: 360
        }
      ];
    //
    // 开始时间
      let start = Cesium.JulianDate.fromDate(new Date(2012,12,8))
    //  结束时间
      let stop = Cesium.JulianDate.addSeconds(start,360 , new Cesium.JulianDate())


      // 设置始时钟始时间
      viewer.clock.startTime = start.clone();
      // 设置时钟当前时间
      viewer.clock.currentTime = start.clone();
      // 设置始终停止时间
      viewer.clock.stopTime = stop.clone();
      // 时间速率，数字越大时间过的越快
      viewer.clock.multiplier = 5;
      // 时间轴
      viewer.timeline.zoomTo(start, stop);

      // 循环执行,即为2，到达终止时间，重新从起点时间开始
      viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP;
      // 好像是 烟雾的初始化位置
      var pos1 = Cesium.Cartesian3.fromDegrees(
        -75.15787310614596,
        39.97862668312678
      );
      var pos2 = Cesium.Cartesian3.fromDegrees(
        -75.1633691390455,
        39.95355089912078
      );
      var position = new Cesium.SampledPositionProperty();

      position.addSample(start, pos1);
      position.addSample(stop, pos2);

      let property = computeFlight(data)
    //  添加模型
      let planeModel = viewer.entities.add({
      //  和时间轴关联
        availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval(({
          start,stop
        }))
        ]),
        position:property,
        orientation:new Cesium.VelocityOrientationProperty(property),
      //  模型数据
        model: {
          uri: 'http://localhost:8888/model/SampleData/models/CesiumAir/Cesium_Air.glb',
          minimumPixelSize: 128
        }
        //现在来一个实体 看看会出现什么结果
        //白色的路劲线条
        // path: new  Cesium.PathGraphics({
        //   material:new Cesium.PolylineGlowMaterialProperty({
        //     glowPower:0.3,
        //     glowColor:Cesium.Color.YELLOWGREEN,
        //     color:Cesium.Color.WHITE
        //   }),
        //   width:3
        // })
      //  需要这个实体 创建一个雷达跟随他 怎么把这个雷达 给他
      })

    //  获取追踪路径
      viewer.trackedEntity = planeModel
      /*
      * 计算飞行路线
      * @param source 数据坐标
      * @returns { sampledPositionProperty}
      * */
      function computeFlight(source){
      //  取样位置 相当于一个集合
        let property = new Cesium.SampledPositionProperty()
        for(let i = 0;i < source.length ; i++){
          let time = Cesium.JulianDate.addSeconds(start,source[i].time,new Cesium.JulianDate())
          let position = Cesium.Cartesian3.fromDegrees(source[i].longitude,source[i].dimension,source[i].height)
        //  添加未知和时间对应
          property.addSample(time,position)
        }
        return property
      }
      var scene = viewer.scene;
      var particleSystem = scene.primitives.add(
        new Cesium.ParticleSystem({
          image: "http://localhost:8888/model/SampleData/smoke.png",

          startColor: Cesium.Color.WHITE.withAlpha(1.0),
          endColor: Cesium.Color.WHITE.withAlpha(0.0),

          startScale: viewModel.startScale,
          endScale: viewModel.endScale,

          minimumParticleLife: viewModel.minimumParticleLife,
          maximumParticleLife: viewModel.maximumParticleLife,

          minimumSpeed: viewModel.minimumSpeed,
          maximumSpeed: viewModel.maximumSpeed,

          imageSize: new Cesium.Cartesian2(
            viewModel.particleSize,
            viewModel.particleSize
          ),

          emissionRate: viewModel.emissionRate,

          bursts: [
            // these burst will occasionally sync to create a multicolored effect
            new Cesium.ParticleBurst({
              time: 2.0,
              minimum: 10,
              maximum: 100
            }),
            new Cesium.ParticleBurst({
              time: 4.0,
              minimum: 50,
              maximum: 100
            }),
            new Cesium.ParticleBurst({
              time: 6.0,
              minimum: 200,
              maximum: 300
            }),
            new Cesium.ParticleBurst({
              time: 8.0,
              minimum: 301,
              maximum: 400
            }),
            new Cesium.ParticleBurst({
              time: 10.0,
              minimum: 400,
              maximum: 500
            })
          ],
          lifetime: 10.0,
          emitter: new Cesium.ConeEmitter(2.0),
          emitterModelMatrix: computeEmitterModelMatrix(),
          updateCallback: applyGravity
        })
      );
      var gravityScratch = new Cesium.Cartesian3();
      // 不知道 是干什么的 草
      function applyGravity(p, dt) {
        // We need to compute a local up vector for each particle in geocentric space.
        var position = p.position;

        Cesium.Cartesian3.normalize(position, gravityScratch);
        Cesium.Cartesian3.multiplyByScalar(
          gravityScratch,
          viewModel.gravity * dt,
          gravityScratch
        );

        p.velocity = Cesium.Cartesian3.add(
          p.velocity,
          gravityScratch,
          p.velocity
        );
      }
      // 每一帧的渲染监听
      let cartographic = null
      let animationContainer = document.getElementById("animationContainer")

      viewer.clock.onTick.addEventListener(clock=>{
        particleSystem.modelMatrix = computeModelMatrix(planeModel, clock.currentTime);

        // Account for any changes to the emitter model matrix.
        particleSystem.emitterModelMatrix = computeEmitterModelMatrix();

        var position = planeModel.position.getValue(clock.currentTime)
        cartographic = Cesium.Cartographic.fromCartesian(position)
        animationContainer.innerHTML = '经度：' + cartographic.longitude.toFixed(2) + '<br/>' + '纬度：' + cartographic.latitude.toFixed(2) + '<br/>' + '高度：' + cartographic.height.toFixed(2) + '<br/>'

      })
      //clock结束的时间触发
      viewer.clock.onStop.addEventListener(function (clock) {
      })
    //  如何把烟雾添加进去 怎么操作 你知道吗
    }
  }
}
</script>
<style scoped lang='scss'>
#cesiumContainer {
  height: 100%;
  width: 100%;
  background-color: red;
  position: relative;
}
#animationContainer{
  position: absolute;
  padding-left: 10px;
  padding-top: 10px;
  right: 0;
  bottom: 100px;
  background-color: rgba(0,0,0,0.5);
  height: 100px;
  width: 300px;
  color: #ffffff;
}
</style>
